<template>
    <el-form ref="formRef" :model="formParams" :rules="rules" label-width="auto">
        <aside class="form-title">高级设置</aside>
        <el-form-item label="助力失效" prop="help_lose_switch" class="form-switch-item">
            <div class="form-switch-tip">
                <el-switch
                    v-model="formParams.help_lose_switch"
                    :active-value="2"
                    :inactive-value="1"
                    :disabled="formDisabled" />
                <span class="form-tip">
                    开启后，助力用户退出企微群后，则助力无效，活动开始后不可编辑。助力失效后其他数据回退：1）助力数据会实时扣减；2）不满足奖品等级条件的奖品库存会释放，兑奖码会失效；3）不满足条件的标签会移除。
                </span>
            </div>
            <el-form-item v-show="isOpen(formParams.help_lose_switch)" label="">
                <el-radio-group v-model="formParams.release_method" class="wrap-radio-group" :disabled="formDisabled">
                    <el-radio :label="1">
                        <span>领奖前可释放</span>
                        <span class="form-tip"> 中奖后但未点击去领奖时，若助力失效不满足奖品等级条件，奖品会释放 </span>
                    </el-radio>
                    <el-radio :label="2">
                        <span>核销前可释放</span>
                        <span class="form-tip">
                            中奖后不管是否领取奖品，只要没有核销，若助力失效不满足奖品等级条件，奖品会释放
                        </span>
                    </el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form-item>
        <el-form-item label="参与限制" prop="join_restrict_switch" class="form-switch-item-center">
            <el-switch v-model="formParams.join_restrict_switch" :active-value="2" :inactive-value="1" />
            <span class="form-tip"> 开启后，活动仅限符合条件的用户参与 </span>
            <template v-if="isOpen(formParams.join_restrict_switch)">
                <el-form-item prop="gender_restrict" required>
                    <template #label>
                        <form-item-label
                            label="性别限制"
                            content="注：只有存量用户有性别信息，微信用户和企业微信用户都不能授权获取到性别信息" />
                    </template>
                    <el-radio-group v-model="formParams.gender_restrict">
                        <el-radio :label="1">不限</el-radio>
                        <el-radio :label="2">男</el-radio>
                        <el-radio :label="3">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item prop="area_restrict" required>
                    <template #label>
                        <form-item-label
                            label="区域限制"
                            content="注：设置区域限制之后，需要用户在参与时授权地理位置信息才可参与活动" />
                    </template>
                    <el-radio-group v-model="formParams.area_restrict">
                        <el-radio :label="1">不限</el-radio>
                        <el-radio :label="2">可参与地区</el-radio>
                        <el-radio :label="3">不可参与地区</el-radio>
                    </el-radio-group>
                    <div v-show="formParams.area_restrict !== 1" class="area-list">
                        <el-cascader
                            v-model="formParams.area_list"
                            :options="cityData"
                            :props="defaultProps"
                            placeholder="请选择地区" />
                    </div>
                </el-form-item>
            </template>
        </el-form-item>
        <el-form-item label="中奖轮播" prop="win_prize_loop_switch" class="form-switch-item loop-switch">
            <el-switch
                v-model="formParams.win_prize_loop_switch"
                :active-value="2"
                :inactive-value="1"
                @change="handleChangePhoneTabs" />
            <span class="form-tip"> 开启后，活动页面上会根据设置轮播样式展示中奖名单 </span>
            <div v-show="isOpen(formParams.win_prize_loop_switch)">
                <el-radio-group v-model="formParams.win_prize_loop_type" @change="handleChangePhoneTabs">
                    <el-radio :label="1">页面滚动</el-radio>
                    <el-radio :label="2">滚动弹幕</el-radio>
                    <el-radio :label="3">轮播弹幕</el-radio>
                </el-radio-group>
            </div>
        </el-form-item>
        <el-form-item label="防刷检测" prop="brush_switch" class="form-switch-item">
            <div class="form-switch-tip">
                <el-switch v-model="formParams.brush_switch" :active-value="2" :inactive-value="1" />
                <span class="form-tip">
                    开启后，用户参与活动会自动根据防刷条件检测，若触发限制，该用户将移入限制名单
                </span>
            </div>
            <div v-show="isOpen(formParams.brush_switch)" class="brush-set">
                如果在
                <form-input-number
                    v-model="formParams.brush_set.time"
                    :min="MIN_NUMBER"
                    :max="60"
                    controls-position="right" />
                秒内，该用户助力人数超过
                <form-input-number
                    v-model="formParams.brush_set.people"
                    :min="MIN_NUMBER"
                    :max="MAX_NUMBER"
                    controls-position="right" />
                人，则自动将该用户加入该活动限制名单
            </div>
        </el-form-item>
        <el-form-item label="奖品余量提醒" prop="inventory_reminder_switch">
            <el-switch
                v-model="formParams.inventory_reminder_switch"
                :active-value="2"
                :inactive-value="1"
                @change="handleReminderWitchChange" />
            <span class="form-tip"> 开启后，奖品剩余数量不足时将给创建人发送企微通知提醒 </span>
            <span class="preview-example" @click="previewExample">查看示例</span>
            <el-dialog v-model="exampleVisible" width="320" title="示例" class="example-dialog" align-center draggable>
                <el-image
                    class="example-image"
                    src="//static.scrm.keyid.cn/assets/images/web-pc/reminder-example.png" />
            </el-dialog>
            <div v-show="isOpen(formParams.inventory_reminder_switch)" class="reminder-set">
                各等级奖品数量小于
                <form-input-number
                    v-model="formParams.inventory_reminder_set.num"
                    :min="MIN_NUMBER"
                    controls-position="right" />
                时发送提醒，提醒周期
                <el-select
                    v-model="formParams.inventory_reminder_set.cycle"
                    placeholder="请选择达成阶梯"
                    :teleported="false"
                    class="cycle-type form-select">
                    <el-option label="余量每减少1" :value="1" />
                    <el-option label="时间间隔" :value="2" />
                </el-select>
                <template v-if="isOpen(formParams.inventory_reminder_set.cycle)">
                    每隔
                    <form-input-number
                        v-model="formParams.inventory_reminder_set.time"
                        :min="MIN_NUMBER"
                        :max="MAX_NUMBER"
                        controls-position="right" />
                    分钟
                </template>
            </div>
        </el-form-item>
        <el-form-item label="自动打标签" prop="auto_tag_switch" class="form-switch-item">
            <div class="form-switch-tip">
                <el-switch v-model="formParams.auto_tag_switch" :active-value="2" :inactive-value="1" />
                <span class="form-tip">
                    开启后，用户参与活动会自动根据规则条件，当符合条件时自动给该用户打上对应的标签，多个规则满足会同时生效
                </span>
            </div>
            <div v-show="isOpen(formParams.auto_tag_switch)">
                <el-tabs
                    v-model="autoTagsIndex"
                    type="card"
                    :closable="formParams.tag_rule.length > 1"
                    addable
                    class="auto-tag-list"
                    @edit="editTabsPane">
                    <el-tab-pane
                        v-for="(item, index) in formParams.tag_rule"
                        :key="index"
                        :label="`规则${numberChineseNameMap[index]}`"
                        :name="index">
                        <el-form-item required class="tags-rule-item">
                            <template #label>
                                <form-item-label label="标签规则">
                                    <template #content>
                                        <div v-html="TAGS_RULE_TIP_CONTENT"></div>
                                    </template>
                                </form-item-label>
                            </template>
                            <el-radio-group v-model="item.type" @change="handleChangeRuleType(item)">
                                <el-radio
                                    v-for="ruleItem in tagsRuleOptions"
                                    :key="ruleItem.label"
                                    :label="ruleItem.label">
                                    {{ ruleItem.name }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <!-- 助力人数 -->
                        <el-form-item
                            v-if="item.type === 7"
                            label="助力人数"
                            :prop="`formParams.tag_rule[${index}].assist_num`"
                            :rules="[{ required: true, ruleIndex: index, validator: checkAssistNum }]"
                            class="assist-num-item">
                            <form-input-number v-model="item.assist_num" :min="1" controls-position="right" />
                        </el-form-item>
                        <!-- 达成阶梯，领取阶梯 -->
                        <el-form-item
                            v-else-if="[9, 13].includes(item.type)"
                            label="达成阶梯"
                            :prop="`formParams.tag_rule[${index}].assist_num`"
                            :rules="[{ required: true, ruleIndex: index, validator: checkAssistNum }]"
                            class="assist-num-item">
                            <el-select
                                v-model="item.assist_num"
                                placeholder="请选择达成阶梯"
                                :teleported="false"
                                class="form-select">
                                <el-option
                                    v-for="(assistItem, assistIndex) in formParams.reward_list"
                                    :key="assistIndex"
                                    :label="`${numberChineseNameMap[assistIndex]}级阶梯`"
                                    :value="assistIndex + 1" />
                            </el-select>
                        </el-form-item>
                        <!-- 裂变级别 -->
                        <el-form-item
                            v-else-if="item.type === 11"
                            label="裂变等级"
                            :prop="`formParams.tag_rule[${index}].assist_num`"
                            :rules="[{ required: true, ruleIndex: index, validator: checkAssistNum }]"
                            class="assist-num-item">
                            <form-input-number v-model="item.assist_num" :min="1" controls-position="right" />
                        </el-form-item>
                        <el-form-item
                            label="选择标签"
                            :prop="`formParams.tag_rule[${index}].tag_ids`"
                            :rules="[{ required: true, ruleIndex: index, validator: checkTagIds }]"
                            class="select-tags">
                            <el-button type="primary" plain @click="openSelectTag(item, index)">
                                <el-icon><Plus /></el-icon>
                                <span>选择标签</span>
                            </el-button>
                            <render-tags v-model:tags="item.tag_ids" />
                        </el-form-item>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </el-form-item>
    </el-form>
    <BatchLabel ref="batchLabelRef" @save="handleSubmitTag" />
</template>
<script lang="ts" setup>
import { ref, reactive, inject } from 'vue';
import { ElMessage, FormRules, FormInstance } from 'element-plus';
import { cloneDeep, max, sum } from 'lodash';
import Decimal from 'decimal.js';
import BatchLabel from '@/components/BatchLabel1.0.vue';
import cityData from '@/assets/js/city';

import formInputNumber from './form-input-number/form-input-number.vue';
import formItemLabel from './form-item-label/form-item-label.vue';
import renderTags from '@/components/zw/activity/render-tags/render-tags.vue';

import { isOpen, TAGS_RULE_TIP_CONTENT, MAX_NUMBER, MIN_NUMBER } from '../utils/index';
import { formParams } from '../utils/paramsManager';
import { ITagItem, ITagData } from '../utils/interface';

const emit = defineEmits(['changePhoneTabs']);
/* ----------------------------城市-start---------------------------- */
const defaultProps = {
    checkStrictly: true, // 是否严格的遵守父子节点不互相关联
    emitPath: false,
    multiple: true,
    label: 'name',
    value: 'code'
};
/* ----------------------------城市-end---------------------------- */

/* ---------------------------表单-start---------------------------- */
const formRef = ref<FormInstance>();

/** 进行中、结束的情况下禁用 */
const formDisabled: any = inject('formDisabled');

// 校验区域
const checkAreaRestrict = (rule: any, value: any, callback: any) => {
    // 未打开区域限制不校验
    if (!isOpen(formParams.join_restrict_switch)) {
        return callback();
    }

    // 设置为不限不校验
    if (formParams.area_restrict === 1) {
        return callback();
    }

    if (!formParams.area_list.length) {
        return callback(new Error('请选择限制区域'));
    }
    callback();
};

// 校验助力人数、达成阶梯、裂变等级
const checkAssistNum = (rule: any, value: any, callback: any) => {
    const { ruleIndex } = rule;
    // 未打开自动打标签不校验
    if (!isOpen(formParams.auto_tag_switch)) {
        return callback();
    }

    // 如果设置的值，则不校验
    if (formParams.tag_rule[ruleIndex].assist_num) {
        return callback();
    }

    // 助力人数校验
    if (formParams.tag_rule[ruleIndex].type === 7) {
        return callback(new Error(`请输入规则${numberChineseNameMap[ruleIndex]}助力人数`));
    }

    // 达成阶梯校验
    if ([9, 13].includes(formParams.tag_rule[ruleIndex].type)) {
        return callback(new Error(`请选择规则${numberChineseNameMap[ruleIndex]}达成阶梯`));
    }

    // 裂变等级校验
    if (formParams.tag_rule[ruleIndex].type === 5) {
        return callback(new Error(`请输入规则${numberChineseNameMap[ruleIndex]}裂变等级`));
    }
    callback();
};

// 选择标签校验
const checkTagIds = (rule: any, value: any, callback: any) => {
    const { ruleIndex } = rule;

    // 未打开自动打标签不校验
    if (!isOpen(formParams.auto_tag_switch)) {
        return callback();
    }

    if (!formParams.tag_rule[ruleIndex].tag_ids.length) {
        return callback(new Error(`请选择规则${numberChineseNameMap[ruleIndex]}标签`));
    }
    callback();
};

// 校验放刷检测
const checkBrushSwitch = (rule: any, value: any, callback: any) => {
    if (!isOpen(formParams.brush_switch)) {
        return callback();
    }
    // 秒数
    if (!formParams.brush_set.time && formParams.brush_set.time !== 0) {
        return callback(new Error('请输入防刷条件秒数'));
    }
    // 人数
    if (!formParams.brush_set.people && formParams.brush_set.people !== 0) {
        return callback(new Error('请输入防刷条件人数'));
    }
    callback();
};

// 校验奖品余量提示
const checkInventoryReminderSwitch = (rule: any, value: any, callback: any) => {
    if (!isOpen(formParams.inventory_reminder_switch)) {
        return callback();
    }
    // 请输入奖品余量提醒的奖品数量
    if (!formParams.inventory_reminder_set.num) {
        return callback(new Error('请输入奖品余量提醒的奖品数量'));
    }

    // 请输入奖品余量提醒的奖品数量
    if (isOpen(formParams.inventory_reminder_set.cycle)) {
        if (!formParams.inventory_reminder_set.time) {
            return callback(new Error('请输入奖品余量提醒的时间间隔'));
        }
    }

    callback();
};
const rules = reactive<FormRules>({
    gender_restrict: [{ required: true, message: '请选择性别限制' }],
    area_restrict: [{ required: true, validator: checkAreaRestrict }],
    brush_switch: [{ validator: checkBrushSwitch }],
    inventory_reminder_switch: [{ validator: checkInventoryReminderSwitch }]
});
/**
 * 校验奖品及其群聊表单
 */
const validate = async () => {
    return await formRef.value?.validate();
};

/* ---------------------------表单-end---------------------------- */

/* ----------------------------奖品余量提示-start---------------------------- */
/** 打开时给奖品个默认值 */
const handleReminderWitchChange = () => {
    // 关闭不设置
    if (!isOpen(formParams.inventory_reminder_switch)) {
        return;
    }

    // 大于1. 代表已经输入过。不需要设置默认值
    if (formParams.inventory_reminder_set.num > 1) {
        return;
    }
    const rewardNumSum = sum(formParams.reward_list.map(item => item.reward_stock));
    const inventoryNum = Math.floor(Number(Decimal.mul(rewardNumSum, 0.05)));
    formParams.inventory_reminder_set.num = max([inventoryNum, 1]) ?? 1;
};

/** 查看示例显示隐藏 */
const exampleVisible = ref(false);
// 查看示例
const previewExample = () => {
    exampleVisible.value = true;
};
/* ----------------------------奖品余量提示-end---------------------------- */

/* ----------------------------打标签-start---------------------------- */
/**
 * @description 当前标签选中的索引
 */
const autoTagsIndex = ref(0);
const numberChineseNameMap = [
    '一',
    '二',
    '三',
    '四',
    '五',
    '六',
    '七',
    '八',
    '九',
    '十',
    '十一',
    '十二',
    '十三',
    '十四',
    '十五'
];

/**
 * 标签规则选择项
 * @description 1: 参与用户
 * @deprecated 2: 邀请人数打标 // 暂无
 * @deprecated 3: 奖品打标 // 暂无
 * @description 4: 助力用户
 * @description 5: 领奖用户
 * @description 6: 中奖用户
 * @description 7: 助力人数
 * @description 8: 核销用户
 * @description 9: 达成阶梯
 * @description 10: 进群用户
 * @description 11: 裂变级别
 * @description 12: 净增用户
 * @description 13: 领取阶梯
 */
const tagsRuleOptions = reactive([
    { label: 1, name: '参与用户' },
    { label: 4, name: '助力用户' },
    { label: 5, name: '领奖用户' },
    { label: 6, name: '中奖用户' },
    { label: 7, name: '助力人数' },
    { label: 8, name: '核销用户' },
    { label: 9, name: '达成阶梯' },
    { label: 10, name: '进群用户' },
    { label: 11, name: '裂变级别' },
    { label: 12, name: '净增用户' },
    { label: 13, name: '领取阶梯' }
]);

/**
 * 切换标签规则类型时重制assist_num
 */
const handleChangeRuleType = (item: ITagItem) => {
    item.assist_num = 1;
};

/**
 * @description 删除/新增tabs栏
 */
const editTabsPane = (targetName: any, action: 'remove' | 'add') => {
    if (action === 'add') {
        addTabsPane();
    } else if (action === 'remove') {
        formParams.tag_rule.splice(targetName, 1);

        // 删除时若超过最后个，则默认选中最后一个
        const lastIndex = formParams.tag_rule.length - 1;
        if (autoTagsIndex.value > lastIndex) {
            autoTagsIndex.value = lastIndex;
        }
    }
};

/**
 * @description 新增tabs栏
 */
const addTabsPane = () => {
    if (formParams.tag_rule.length >= 15) {
        ElMessage.warning('已达添加上线15个');
        return;
    }
    formParams.tag_rule.push({
        type: 1,
        assist_num: 1,
        tag_ids: []
    });
    autoTagsIndex.value = formParams.tag_rule.length - 1;
};
/**
 * @description 选择标签弹窗实例
 */
const batchLabelRef = ref<any>();
/**
 * @description 暂存的打标签的数据源
 */
let tagItemcache: ITagItem | null = null,
    tagIndexcache = 0;

/**
 * @param data ITagItem
 * @description 选择标签弹窗实例
 */
const openSelectTag = (data: ITagItem, index: number) => {
    tagItemcache = data;
    tagIndexcache = index;
    batchLabelRef.value.chooseDataArr = [...data.tag_ids];
    batchLabelRef.value.dialogVisible = true;
    batchLabelRef.value.hasConditiion = false;
    batchLabelRef.value.dialogData.labelChooseType = 2;
};

/**
 * @param data ITagItem
 * @description 提交已选择标签
 */
const handleSubmitTag = (data: ITagData) => {
    tagItemcache?.tag_ids.splice(0);
    tagItemcache?.tag_ids.push(...cloneDeep(data.data));
    formRef.value?.clearValidate([`formParams.tag_rule[${tagIndexcache}].tag_ids`]);
};
/* ----------------------------打标签-end---------------------------- */
/** 改变外部样机tabs */
const handleChangePhoneTabs = () => {
    if (!isOpen(formParams.win_prize_loop_switch)) {
        // 默认不传。样机会自动判断
        emit('changePhoneTabs');
        return;
    }

    // 根据打开的类型，手动切换tabs当前选中。然后滚动至tabs组件的位置
    // 如果tabs没有，则传入的选择器，会在样机中查询选择器，如若查询到。则会滚动至页面位置。
    const loopTypeTabs = { 1: 'winnersList', 2: '#barrageRoll', 3: '#barrageLoop' }[formParams.win_prize_loop_type];
    emit('changePhoneTabs', loopTypeTabs);
};
defineExpose({
    validate
});
</script>
